﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.Mvc;
using GsnHelper;
using ZhongheCms.Models;
using Qiniu.Conf;
using Qiniu.IO.Resumable;
using Qiniu.RS;

namespace ZhongheCms.Controllers
{
    public class GsnServiceController : Controller
    {
        //
        // GET: /GsnService/
        public JsonResult CheckUserName(string memberUserName)
        {
            var isValidate = !GswTblMember.Exists("MemberUserName='" + memberUserName + "'");
            return Json(isValidate, JsonRequestBehavior.AllowGet);
        }

        public JsonResult CheckVerifyCode(string verifyCodePic)
        {
            bool isValidate = Session["ValidateCode"].ToString() == verifyCodePic;
            return Json(isValidate, JsonRequestBehavior.AllowGet);
        }
        public JsonResult UploadFileToQiniu()
        {
            HttpPostedFileBase fileData = Request.Files[0];
            if (fileData == null)
                return Json(new { Success = false, Message = "请选择要上传的文件！" }, JsonRequestBehavior.AllowGet);


            Config.ACCESS_KEY = "9hSrJSwMyZua538MfMlzUtjnamR_3xgOQqGgj0EI";
            Config.SECRET_KEY = "a84YTNjKVE8w4shX6HjnXFVV4iN1ShE1fbgMAq7g";
            var policy = new PutPolicy("zhongheweb", 3600);
            var upToken = policy.Token();
            var setting = new Settings();
            var extra = new ResumablePutExtra();
            var client = new ResumablePut(setting, extra);
            var fileName = fileData.FileName;
            var fileExtension = Path.GetExtension(fileName); // 文件扩展名
            var saveName = Guid.NewGuid() + fileExtension; // 保存文件名称
            try
            {
                var ret = client.PutFile(upToken, fileData.InputStream, saveName);
                return ret.OK ? Json(new { Success = true, FileName = fileName, SaveName = saveName, SavePath = "http://zhongheweb.qiniudn.com/" }) : Json(new { Success = false, Message = "文件上传失败" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {

                return Json(new { Success = false, ex.Message }, JsonRequestBehavior.AllowGet);
            }


        }
        [HttpPost]
        public JsonResult UploadPic(int id = 0, int cid = 0)
        {
            HttpPostedFileBase fileData = Request.Files[0];
            if (fileData == null)
                return Json(new { Success = false, Message = "请选择要上传的文件！" }, JsonRequestBehavior.AllowGet);

            try
            {
                // 文件上传后的保存路径
                string mypath = "~/Upload/";
                if (cid > 0)
                {
                    var customer = GswTblCustomer.SingleOrDefault(cid);
                    if (customer != null)
                    {
                        if (!string.IsNullOrEmpty(customer.CustomerNo))
                        {
                            mypath += customer.CustomerNo.Trim() + "/";
                        }
                    }
                }
                string filePath = Server.MapPath(mypath);
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }
                string fileName = Path.GetFileName(fileData.FileName);// 原始文件名称
                string fileExtension = Path.GetExtension(fileName); // 文件扩展名
                string saveName = Guid.NewGuid().ToString() + fileExtension; // 保存文件名称
                fileData.SaveAs(filePath + saveName);
                return Json(new { Success = true, FileName = fileName, SaveName = saveName, SavePath = mypath.Substring(1, mypath.Length - 1) });
            }
            catch (Exception ex)
            {
                return Json(new { Success = false, ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        public JsonResult GetJobType(string id = "", string cusid = "", string term = "", string initid = "", string p = "")
        {

            var fid = 120;
         
            var sql = " select Id as id ,MasterType as text from GswTblBaseInfo where FunctionId=" + fid + " and  CustomerId=" + cusid;


            if (!string.IsNullOrEmpty(term))
                sql += " and (MasterType like '%" + term + "%')";
            if (InputValid.IsNumber(initid))
                sql += " and Id=" + initid;
            sql += " order by TypeNo";
            var qry = GswTblCustomer.repo.Fetch<Select2Result>(sql);
            var pageResult = new Select2PagedResult { Results = qry, Total = 1 };
            return Json(pageResult, JsonRequestBehavior.AllowGet);
        }
        public JsonResult GetShareType(string id = "", string cusid = "", string term = "", string initid = "", string p = "")
        {

            var fid = 86;
          
            var sql = " select Id as id ,MasterType as text from GswTblBaseInfo where FunctionId=" + fid + " and  CustomerId=" + cusid;


            if (!string.IsNullOrEmpty(term))
                sql += " and (MasterType like '%" + term + "%')";
            if (InputValid.IsNumber(initid))
                sql += " and Id=" + initid;
            sql += " order by TypeNo";
            var qry = GswTblCustomer.repo.Fetch<Select2Result>(sql);
            var pageResult = new Select2PagedResult { Results = qry, Total = 1 };
            return Json(pageResult, JsonRequestBehavior.AllowGet);
        }
        public JsonResult GetProType(string id = "", string cusid = "", string term = "", string initid = "", string p = "")
        {

            var fid = 5;
            if (!string.IsNullOrEmpty(p))
            {
                var funs = GswTblFunction.SingleOrDefault("where FuncName='产品类别' and ActionParam='" + p + "'");
                if (funs != null)
                {
                    fid = funs.Id;
                }
            }
            var sql = " select Id as id ,MasterType as text from GswTblBaseInfo where FunctionId=" + fid + " and  CustomerId=" + cusid;


            if (!string.IsNullOrEmpty(term))
                sql += " and (MasterType like '%" + term + "%')";
            if (InputValid.IsNumber(initid))
                sql += " and Id=" + initid;
            sql += " order by TypeNo";
            var qry = GswTblCustomer.repo.Fetch<Select2Result>(sql);
            var pageResult = new Select2PagedResult { Results = qry, Total = 1 };
            return Json(pageResult, JsonRequestBehavior.AllowGet);
        }



        public JsonResult GetProjectType(string id = "", string cusid = "", string term = "", string initid = "", string p = "")
        {
            var sql = " select Id as id ,MasterType as text from GswTblBaseInfo where RelateId=" + id + " and  CustomerId=" + cusid;


            if (!string.IsNullOrEmpty(term))
                sql += " and (MasterType like '%" + term + "%')";
            if (InputValid.IsNumber(initid))
                sql += " and Id=" + initid;
            sql += " order by TypeNo";
            var qry = GswTblCustomer.repo.Fetch<Select2Result>(sql);
            var pageResult = new Select2PagedResult { Results = qry, Total = 1 };
            return Json(pageResult, JsonRequestBehavior.AllowGet);
        }
        public JsonResult GetProInfo(string id = "", string cusid = "", string term = "", string initid = "", string p = "")
        {
            var fid = 7;
            if (!string.IsNullOrEmpty(p))
            {
                var funs = GswTblFunction.SingleOrDefault("where FuncName='产品信息' and ActionParam='" + p + "'");
                if (funs != null)
                {
                    fid = funs.Id;
                }
            }
            var sql = " select Id as id ,ProName as text from GswTblProInfo where FunctionId=" + fid + " and  CustomerId=" + cusid;
            if (!string.IsNullOrEmpty(term))
                sql += " and (ProName like '%" + term + "%')";
            if (InputValid.IsNumber(initid))
                sql += " and Id=" + initid;
            sql += " order by ProNo";
            var qry = ZhongheRepo.GetInstance().Fetch<Select2Result>(sql);
            var pageResult = new Select2PagedResult { Results = qry, Total = 1 };
            return Json(pageResult, JsonRequestBehavior.AllowGet);
        }
        public JsonResult GetJobCustomer(string id = "", string term = "", string initid = "")
        {

            var sql = " select Id as id ,CusShortName as text from GswTblJobCustomer where  SourceFlag=1 and  ParentId=" + id;
            if (!string.IsNullOrEmpty(term))
                sql += " and (CusShortName like '%" + term + "%')";
            if (InputValid.IsNumber(initid))
                sql += " and Id=" + initid;
            sql += " order by CustomerNo";
            var qry = ZhongheRepo.GetInstance().Fetch<Select2Result>(sql);
            var pageResult = new Select2PagedResult { Results = qry, Total = 1 };
            return Json(pageResult, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetValidateCode()
        {
            var vCode = new ValidateCode();
            string code = vCode.CreateValidateCode(5);
            Session["ValidateCode"] = code;
            byte[] bytes = vCode.CreateValidateGraphic(code);
            return File(bytes, @"image/jpeg");
        }
    }
    public class Select2PagedResult
    {
        public int Total { get; set; }
        public List<Select2Result> Results { get; set; }
    }

    public class Select2Result
    {
        public string id { get; set; }
        public string text { get; set; }
    }
}
